package com.example.mptnet;

import static android.content.Context.MODE_PRIVATE;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mptnet.Adapters.RecyclerViewAdapter;
import com.example.mptnet.Interfaces.API;
import com.example.mptnet.Models.RP;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class rp_fragment extends Fragment {
    SharedPreferences settings;
    SharedPreferences.Editor edit;
    API api;
    Retrofit retrofit;
    ListView listview;
    ArrayList<RP> rp = new ArrayList<RP>();
    RecyclerView recyclerView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_rp_fragment, container, false);
        settings = getContext().getApplicationContext().getSharedPreferences("SETTINGS", MODE_PRIVATE);
        edit = settings.edit();
        if(!settings.contains("group") || settings.getString("group", "").equals(""))
            Toast.makeText(getContext(),"Группа не была найдена в вашем профиле!", Toast.LENGTH_LONG).show();
        else{
            recyclerView = view.findViewById(R.id.recycler);
            retrofit = Builder.request();
            api = retrofit.create(API.class);
            String group = settings.getString("group","");
            Call<ArrayList<RP>> callRP = api.GetRP(group);
            callRP.enqueue(new Callback<ArrayList<RP>>() {
                @Override
                public void onResponse(Call<ArrayList<RP>> call, Response<ArrayList<RP>> response) {
                    if(response.isSuccessful()){
                        recyclerView.setLayoutManager(new LinearLayoutManager(getContext().getApplicationContext()));
                        recyclerView.setHasFixedSize(true);
                        rp = response.body();
                        RecyclerViewAdapter rv = new RecyclerViewAdapter(getContext().getApplicationContext(),rp);
                        recyclerView.setAdapter(rv);
                    }
                }

                @Override
                public void onFailure(Call<ArrayList<RP>> call, Throwable t) {
                    Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show();
                }
            });
        }

        return view;
    }
}